import React, { Component } from 'react';
import { DrillDownMap } from '@/components/Charts';

export default class DrillDownMapDemo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentAreaNumber: '',
    };
  }

  componentWillMount() {
    const { areaNumber } = this.props;
    if (areaNumber) {
      this.setState({ currentAreaNumber: areaNumber });
    }
  }

  componentWillReceiveProps(nextProps) {
    const { areaNumber } = this.props;
    if (nextProps.areaNumber && nextProps.areaNumber !== areaNumber) {
      this.setState({ currentAreaNumber: nextProps.areaNumber });
    }
  }

  shouldComponentUpdate(nexProps, nextState) {
    const { currentAreaNumber } = this.state;
    return !(
      currentAreaNumber === nextState.currentAreaNumber && currentAreaNumber !== nexProps.areaNumber
    );
  }

  onMapClick = (newAreaNumber, areaCN, isLabelClick) => {
    const { currentAreaNumber } = this.state;
    const { areaNumber, areaList, onMapClick } = this.props;
    let level = 'province';
    let newAreaList = [];
    if (newAreaNumber !== areaNumber && currentAreaNumber === areaNumber) {
      level = 'city';
      newAreaList = areaList.splice(0, 1);
      newAreaList.push(areaCN);
    } else if (newAreaNumber !== areaNumber && currentAreaNumber !== areaNumber) {
      level = 'county';
      if ((isLabelClick && level === 'county') || !areaCN) return; // 取消县级标签点击事件
      newAreaList = areaList.splice(0, 2);
      newAreaList.push(areaCN);
    } else {
      newAreaList = areaList.splice(0, 1);
    }
    if (currentAreaNumber === areaNumber || newAreaNumber === areaNumber)
      this.setState({ currentAreaNumber: newAreaNumber });
    if (onMapClick) {
      if (isLabelClick && level === 'county') return; // 取消县级标签点击事件
      onMapClick(level, areaCN, newAreaNumber, newAreaList);
    }
  };

  render() {
    const { currentAreaNumber } = this.state;
    const { areaNumber } = this.props;
    return (
      <div>
        <DrillDownMap
          areaNumber={currentAreaNumber}
          drillDown
          width={600 * window.viewportScale}
          height={650 * window.viewportScale}
          onMapClick={this.onMapClick}
        />
        {currentAreaNumber && currentAreaNumber !== areaNumber && (
          <div style={{ position: 'absolute', right: 0, bottom: 0 }}>
            <DrillDownMap
              areaNumber={areaNumber}
              width={200 * window.viewportScale}
              onMapClick={this.onMapClick}
            />
          </div>
        )}
      </div>
    );
  }
}
